package com.string.proxy;

import com.string.service.AccountService;
import com.string.service.IAccountService;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class ServiceProxy {
    public static void main(String[] args) {
        AccountService accountService = new AccountService();
        //accountService.transfer("a","b",100);
//实现加载器
        IAccountService proxy = (IAccountService) Proxy.newProxyInstance(accountService.getClass().getClassLoader(), accountService.getClass().getInterfaces(),
                new InvocationHandler() {
                    @Override
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                        try {
                            System.out.println("开始事务");
                            Object invoke = method.invoke(accountService, args);
                            System.out.println("提交事务");
                            return invoke;

                        }catch (Exception e){
                            System.out.println("回滚事务");
                        }
                        return null;
                    }
                });
        proxy.transfer("a","b",100);
    }
}
